﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.Xml;

namespace WcfServiceLibrary
{
    public class RssHelper
    {
        public static List<CustomSyndicationItem> Get_RSS(string urlRSS)
        {
            List<CustomSyndicationItem> _itemRss = new List<CustomSyndicationItem>();
            string localUrlRss = urlRSS;
            if (string.IsNullOrEmpty(localUrlRss))
            {
                throw new Exception("Invalid paramter in get rss function !");
            }
            // Split to multi rss link
            string[] multiRss = localUrlRss.Split(';');
            // Init variables
            CustomSyndicationItem _tempItem = null;

            try
            {
                // Get item to each rss link
                foreach (var urlItem in multiRss)
                {
                    // Read above rss
                    SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(urlItem));
                    string generator = (feed.Links.Count < 1) ? string.Empty : feed.Links[0].Uri.Host;
                    string description = (feed.Links.Count < 1) ? string.Empty : feed.Description.ToString();
                    // Each item in rss list
                    foreach (var item in feed.Items)
                    {
                        if (item is SyndicationItem)
                        {
                            _tempItem = new CustomSyndicationItem(item.Title.Text, string.Empty,
                                item.PublishDate.DateTime,item.Summary.Text,
                                (item.Links.Count < 1) ? string.Empty : item.Links[0].Uri.AbsoluteUri, generator);
                            // Add item to rss list
                            _itemRss.Add(_tempItem);
                        }
                    }
                }
                // Filter item by updated date
                //_itemRss.OrderByDescending(i => i.UpdatedTime);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            // Filter rss by lasted update time

            return _itemRss;
        }
    }
}
